package com.echo.im.client.handler.suport;

import com.echo.im.client.handler.suport.platform.PlatformMessageHandler;
import com.echo.im.common.exception.BeansException;
import com.echo.im.common.model.message.platform.PlatformMessage;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * PlatformCmdHandler handles the sending of platform commands.
 * It uses a generic PlatformCommandMessageEvent to handle specific command data types.
 *
 * @author echo
 * @time 2024-08-16
 */
public abstract class AbstractPlatformMessageHandler<T extends PlatformMessage> implements PlatformMessageHandler<T> {

    @Override
    public boolean support(PlatformMessage platformMessage) {
        // 获取当前类的直接父类的类型信息
        Type genericSuperclass = this.getClass().getGenericSuperclass();

        // 获取第一个泛型参数类型
        Type actualTypeArgument = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
        String className = actualTypeArgument.getTypeName();

        // 尝试加载类型参数所指定的类
        Class<?> eventClassName;
        try {
            eventClassName = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new BeansException("错误的事件类名: " + className, e);
        }

        // 判断 platformCmd 的类是否为泛型类或其子类
        return eventClassName.isAssignableFrom(platformMessage.getClass());
    }
}
